package com.elinkway.infinitemovies.ui.activity.play;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.elinkway.infinitemovies.bean.PlayData;
import com.elinkway.infinitemovies.ui.activity.play.VideoPlayerScreenListener.ScreenStateListener;
import com.elinkway.infinitemovies.utils.DialogUtil;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.TrafficStatsUtil;
import com.elinkway.infinitemovies.utils.Utils;
import com.le123.ysdq.R;
import com.umeng.analytics.MobclickAgent;

public class PlayActivityLive extends Activity implements OnClickListener{
    
    private ImageView mPlayBack;
    
    private final static String TAG = "PlayActivityLive";
    
    private int mSysAPILevel = 0;
    
    public boolean isFromBackground = false;//从后台切换回来，解决暂停时，从后台切换回来播放从头开始的bug
    
    /**
     * 用户是否选择了在3G网络下播放
     */
    private boolean mIsWifiTo3GFlag;

    private boolean isClickBack = false;
    
    private Window mWindow;
    
    private PlayLiveController mLiveController;
    
    private VideoPlayerScreenListener mSceenListener;

    // wuxinrong deleted begin
    // 都已经是单例模式了，创建你妹的对象
    //private DialogUtil dialogUtil;
    // wuxinrong deleted end

    private PlayData mPlayData;
    
    private HandlerInterface mHandlerCallback;
    
    private NetworkCheckReceiver mCheckReceiver;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_liveplayer);
        doNotLockScreen();
        initData();
    }
    
    /**
     * 设置当前屏幕不锁屏 
     * zhangshuo
     * 2015年2月3日 上午10:47:14
     */
    private void doNotLockScreen() {
        mWindow = getWindow();
        // 设置当前屏幕不锁屏
        mWindow.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }
    
    private void initData() {
        mPlayBack = (ImageView)findViewById(R.id.videoplayer_playback_btn);
        mPlayBack.setOnClickListener(this);
        mSysAPILevel = Utils.getAPILevel();
        initTrafficStats(mSysAPILevel);

        Intent intent = getIntent();
        if (null != intent) {
            setWifiTo3GFlag(intent.getBooleanExtra(Utils.PLAY_3G_NET, false));
        }

        mLiveController = new PlayLiveController(this);
        // 创建屏幕监听且
        mSceenListener = new VideoPlayerScreenListener(this);
        // 注册屏幕监听广播 并实现屏幕状态监听
        mSceenListener.begin(new PlayerScreenSateListener());
        // wuxinrong modified begin
        //dialogUtil = new DialogUtil(this);
        // wuxinrong modified end
        mHandlerCallback = new HandlerInterfaceImpl();
        registerCheckNetwork();
        if (null != intent && null != intent.getSerializableExtra(Utils.PLAY_DATA)) {
            mPlayData = (PlayData) intent.getSerializableExtra(Utils.PLAY_DATA);
            // 将播放数据提供给播放控制台使用
            mLiveController.setmPlayData(mPlayData);
        }
    }

    /**
     * 监听手机网络变化 
     */
    protected void registerCheckNetwork() {
        mCheckReceiver = new NetworkCheckReceiver();
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(PlayerUtils.CONNECTIVTY_CHANGE);
        this.registerReceiver(mCheckReceiver, intentfilter);
    }

    /**
     * 取消注册检查网络变化*
     */
    protected void unregisterCheckNetwork() {
        if (mCheckReceiver != null) {
            try {
                this.unregisterReceiver(mCheckReceiver);
            } catch (IllegalArgumentException e) {
                if (e.getMessage().contains("Receiver not registered")) {
                    LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!ignore incorrect unregisterCheckNetwork!!!!!!!!!!!!!!!!!");
                    // Ignore this exception. This is exactly what is desired
                } else {
                    // unexpected, re-throw
                    throw e;
                }
            }
        }
    }

    /**
     * 检测当前网络状态
     * 
     * 
     */
    class NetworkCheckReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && !getWifiTo3GFlag()) {
                checkNetwork(intent);
            }
        }
    }

    protected void checkNetwork(Intent intent) {
        if (mHandlerCallback != null) {
            // 读取保存的之前网络状态
            SharedPreferences priorNetState =
                    getSharedPreferences("priornetstate", Activity.MODE_PRIVATE);
            int priorNetType = priorNetState.getInt("netstate", 2);
            // wuxinrong modified begin
            DialogUtil instance = DialogUtil.getInstance(PlayActivityLive.this);
            int nowNetType =
                    mHandlerCallback.checkNetwork(this, intent, mLiveController, instance,
                            priorNetType);
            // wuxinrong modified end
            SharedPreferences.Editor editor = priorNetState.edit();
            editor.putInt("netstate", nowNetType);
            editor.commit();
        }
    }
    
    /**
     * 动态展现状态栏 使用这种方式能够使系统状态栏浮在最顶层显示而不占用Activity空间
     * @param enable
     * zhangshuo
     * 2014年5月5日 上午10:54:02
     */
    public void statusBarShow(boolean enable) {
        Window window = getWindow();
        if (enable) {
            WindowManager.LayoutParams attr = window.getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            window.setAttributes(attr);
        } else {
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            window.setAttributes(lp);
        }
    }
    
    /**
     * 屏幕状态监听实现类
     * @author zhangshuo
     *
     */
    public class PlayerScreenSateListener implements ScreenStateListener {

        @Override
        public void onScreenOn() {
            
        }

        @Override
        public void onScreenOff() {
            
        }

        @Override
        public void onUserPresent() {
            if (!Utils.getScreenLockStatus() && null != mLiveController){
                PlayerUtils.sendPlayingBroadcast(PlayActivityLive.this);
            }
        }
        
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        PlayerUtils.sendNotPlayingBroadcast(PlayActivityLive.this);
        // 停止播放器页面刷新
        if (null != mLiveController) {
            mLiveController.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        if (!Utils.getScreenLockStatus() && null != mLiveController){
            mLiveController.onResume();
        }
    }
    
    

    @Override
    protected void onStop() {
        super.onStop();
        //Toast.makeText(this, "!!!!!onStop!!!!!!", Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        isFromBackground = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSceenListener.unregisterListener();
        setWifiTo3GFlag(false);
        unregisterCheckNetwork();
        isFromBackground = false;
    }
    
    /**
     * 初始化网速
     * @param sdkVersion
     * zhangshuo
     * 2014年8月19日 下午2:06:31
     */
    private void initTrafficStats(int sdkVersion) {
        if (sdkVersion >= 8) {
            TrafficStatsUtil.getPreRxByte();
        }
    }

    public void setWifiTo3GFlag(boolean flag){
        mIsWifiTo3GFlag = flag;
    }

    public boolean getWifiTo3GFlag() {
        return mIsWifiTo3GFlag;
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && 0 == event.getRepeatCount()) {
            isClickBack = true;
            return true;
        }
        return false;
    }
    
    public int getmSysAPILevel() {
        return mSysAPILevel;
    }
    
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP && isClickBack) {
            LogUtils.e(TAG, "!!!!!!!!!!!dispatchKeyEvent!!!!!!!!");
            exitEvent();
            isClickBack = false;
        }
        return super.dispatchKeyEvent(event);
    }

    public Window getmWindow() {
        return mWindow;
    }
    
    private void exitEvent(){
        if (null != mLiveController) {
            mLiveController.exitNormal();
        }
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.videoplayer_playback_btn:
                exitEvent();
                break;
            default:
                break;
        }

    }
}
